package com.bjshiwei.zhengu.ui.fragment;


import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.bjshiwei.zhengu.R;
import com.bjshiwei.zhengu.adapter.IndividualAdapter;
import com.bjshiwei.zhengu.bean.IndividualBean;
import com.bjshiwei.zhengu.bean.IndividualList;
import com.bjshiwei.zhengu.bean.UserBean;
import com.bjshiwei.zhengu.config.NetConfig;
import com.bjshiwei.zhengu.requestInfo.RequestListenerInfo;
import com.bjshiwei.zhengu.utils.IndividualDao;
import com.bjshiwei.zhengu.utils.PrefUtil;
import com.bjshiwei.zhengu.utils.SerializationUtil;
import com.bjshiwei.zhengu.utils.VolleyRequest;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class IndividualDetailFragment extends BaseFragment {


    private PullToRefreshListView mListView;
    private VolleyRequest mVolleyRequest;
    private List<IndividualBean.DataBean> mDataBeen;
    private IndividualAdapter mIndividualAdapter;
    private PrefUtil mPrefUtil;
    private SerializationUtil mSerializationUtil;
    private String mUserId;
    private String mLoginId;
    private List<IndividualList.Data> mDataList;
    private IndividualList mIndividualList;
    private Intent mIntent;
    private ImageView mImageViewEmpty;
    private RelativeLayout mRelativeLayoutSearch;
    private ImageView mImageViewZhangFu;
    private LinearLayout mLinearLayoutZhangfu;
    public static  final  int[] ZHANGFU= {R.mipmap.zhangfu_dj1,R.mipmap.zhangfu_dj2,R.mipmap.zhangfu_nor};
    private int clickNum = 0;
    private String nowRequestStr = "";
    private IndividualDao mIndividualDao;
    private ImageView mImageViewTop;
    @Override
    protected void setListener() {

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(firstVisibleItem>10) {
                    mImageViewTop.setVisibility(View.VISIBLE);
                }else{
                    mImageViewTop.setVisibility(View.GONE);
                }
            }
        });

        mImageViewTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { mListView.getRefreshableView().setSelection(0);
//                mListView.getRefreshableView().smoothScrollToPosition(0);

            }
        });

       /* mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mIntent = new Intent(getActivity(), MarketDetailActivity.class);
                String stockId = mDataBeen.get(position-1).getCode();
                String name = mDataBeen.get(position-1).getName();
                mIntent.putExtra("id",stockId);
                mIntent.putExtra("name",name);
                startActivity(mIntent);
            }
        });

        mRelativeLayoutSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIntent = new Intent(getActivity(), SearchActivity.class);
                startActivity(mIntent);
            }
        });*/

        mLinearLayoutZhangfu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (clickNum) {
                    case 0 :
                        mImageViewZhangFu.setImageResource(ZHANGFU[0]);
                        clickNum++;
                        nowRequestStr = "up";
                        break;
                    case 1:
                        mImageViewZhangFu.setImageResource(ZHANGFU[1]);
                        clickNum++;
                        nowRequestStr = "down";
                        break;
                    case 2:
                        mImageViewZhangFu.setImageResource(ZHANGFU[2]);
                        nowRequestStr = "";
                        clickNum = 0;
                        break;
                }
                getData(nowRequestStr);

            }
        });

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                getData(nowRequestStr);
                ILoadingLayout startLabels = mListView.getLoadingLayoutProxy(true, false);
                //设置下拉标签
                startLabels.setPullLabel("下拉刷新");
                //设置刷新标签
                startLabels.setRefreshingLabel("正在刷新");
                //设置释放标签
                startLabels.setReleaseLabel("释放开始刷新");
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getData(nowRequestStr);
    }

    @Override
    protected void setData() {
        mListView.setAdapter(mIndividualAdapter);
    }

    @Override
    protected void initData() {
        mIndividualDao = new IndividualDao(getContext());
        mDataList= new ArrayList<>();
        mIndividualList = new IndividualList();
        mPrefUtil = PrefUtil.getInstance(getContext());
        mSerializationUtil = SerializationUtil.getInstance(getContext());
        mDataBeen = new ArrayList<>();
        mIndividualAdapter = new IndividualAdapter(getContext(),mDataBeen);
    }


    @Override
    protected View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_individual_detail, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mListView = (PullToRefreshListView) view.findViewById(R.id.lv_individual_body);
        mImageViewEmpty = (ImageView) view.findViewById(R.id.iv_empty_view);
        mRelativeLayoutSearch = (RelativeLayout) view.findViewById(R.id.rl_search);
        mImageViewZhangFu = (ImageView) view.findViewById(R.id.iv_individual_zhangfu);
        mLinearLayoutZhangfu = (LinearLayout) view.findViewById(R.id.ll_individual_zhangfu);
        mListView.setEmptyView(mRelativeLayoutSearch);
        mImageViewTop = (ImageView) view.findViewById(R.id.iv_individual_detail_totop);
    }


    public void getData(String requestStr) {
        String user = mPrefUtil.getUser();
        if(user!=null){
            mSerializationUtil = SerializationUtil.getInstance(getContext());
            try {
                UserBean userBean = (UserBean) mSerializationUtil.deSerialization(user);
                String uid = userBean.getUid();
                String loginid = userBean.getLoginid();
                mUserId = uid;
                mLoginId = loginid;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            Map<String,String> params = new HashMap<String, String>();
            params.put("userid", mUserId);
            params.put("loginid", mLoginId);
            params.put("rank",requestStr);

            mVolleyRequest = VolleyRequest.getInstance(getContext());
            mVolleyRequest.stringPoastRequest(NetConfig.INDIVIDUAL_DETAIL, params, new RequestListenerInfo(getActivity()) {
                @Override
                protected void onAnalysis(Object o, JSONObject jsonObject, boolean success) {
                    mDataBeen.clear();
                    Gson gson = new Gson();
                    IndividualBean individualBean = gson.fromJson(o.toString(), IndividualBean.class);
                    for (int i = 0; i < individualBean.getData().size(); i++) {
                        mDataBeen.add(individualBean.getData().get(i));
                        String code = mDataBeen.get(i).getCode();
                        IndividualList.Data data = new IndividualList.Data();

                        Cursor sw = mIndividualDao.findAll("sw", new String[]{"code"}, "code=?", new String[]{code});
                        if(sw.getCount()==0) {
                            ContentValues values = new ContentValues();
                            values.put("code",code);
                            mIndividualDao.insert("sw",values);
                        }
                        data.setCode(code);
                        mDataList.add(data);
                    }
                    mIndividualAdapter.notifyDataSetChanged();
                    mIndividualList.setData(mDataList);

                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 500);
                }
            });
        }else{
            mDataBeen.clear();
            mIndividualAdapter.notifyDataSetChanged();
            mListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mListView.onRefreshComplete();
                }
            }, 500);
        }
    }
}
